const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');
const fs = require('fs');
const WebSocket = require('ws');
const chokidar = require('chokidar');

const app = express();
const port = 3000;

// WebSocket服务器
const wss = new WebSocket.Server({ port: 8080 });

// 存储所有连接的客户端
const clients = new Set();

// WebSocket连接处理
wss.on('connection', (ws) => {
    clients.add(ws);
    ws.on('close', () => clients.delete(ws));
});

// 监听文件变化
const watcher = chokidar.watch(path.join(__dirname, 'pages'), {
    ignored: /(^|[\/\\])\../, // 忽略隐藏文件
    persistent: true
});

watcher.on('change', (path) => {
    // 当文件发生变化时，通知所有客户端刷新
    clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send('refresh');
        }
    });
});

// 注入刷新脚本的中间件
app.use((req, res, next) => {
    if (req.path.endsWith('.html')) {
        const filePath = path.join(__dirname, req.path);
        fs.readFile(filePath, 'utf8', (err, data) => {
            if (err) {
                next();
                return;
            }

            // 注入WebSocket客户端代码
            const injectedScript = `
                <script>
                    (function() {
                        const ws = new WebSocket('ws://localhost:8080');
                        ws.onmessage = function(event) {
                            if (event.data === 'refresh') {
                                window.location.reload();
                            }
                        };
                    })();
                </script>
            `;

            // 在</body>标签前注入脚本
            const modifiedHtml = data.replace('</body>', injectedScript + '</body>');
            res.send(modifiedHtml);
        });
    } else {
        next();
    }
});

// 静态文件服务
app.use(express.static(path.join(__dirname)));

// 接口代理配置
const proxyOptions = {
    target: 'https://api.example.com',
    changeOrigin: true,
    pathRewrite: {
        '^/api': ''
    }
};

// 添加接口代理中间件
app.use('/api', createProxyMiddleware(proxyOptions));

// 需要忽略的目录
const ignoreDirs = ['css', 'js', 'images', 'img', 'fonts', 'assets'];

// 获取pages目录下所有HTML页面的路径
function getAllPages(dirPath, baseUrl = '') {
    const result = {};
    const items = fs.readdirSync(dirPath);

    items.forEach(item => {
        const fullPath = path.join(dirPath, item);
        const stat = fs.statSync(fullPath);

        if (stat.isDirectory() && !ignoreDirs.includes(item.toLowerCase())) {
            // 只处理非忽略的目录
            const subPages = getAllPages(fullPath, `${baseUrl}/${item}`);
            // 只有当子目录包含页面时才添加
            if (Object.keys(subPages).length > 0) {
                result[item] = subPages;
            }
        } else if (item.endsWith('.html')) {
            if (!result.pages) {
                result.pages = [];
            }
            result.pages.push(`${baseUrl}/${item}`);
        }
    });

    return result;
}

// 打印页面树结构
function printPagesTree(pagesTree, baseUrl, level = 0) {
    const indent = '  '.repeat(level);

    for (const [key, value] of Object.entries(pagesTree)) {
        if (key === 'pages') {
            value.forEach(page => {
                console.log(`${indent}├─ ${baseUrl}${page}`);
            });
        } else {
            console.log(`${indent}${key}/`);
            printPagesTree(value, baseUrl, level + 1);
        }
    }
}

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
    console.log(`WebSocket服务器运行在 ws://localhost:8080`);

    const pagesDir = path.join(__dirname, 'pages');
    const pagesTree = getAllPages(pagesDir);
    const baseUrl = `http://localhost:${port}/pages`;

    console.log('\n可访问的页面路径：');
    printPagesTree(pagesTree, baseUrl);
}); 